<template>
  <div class="organize-tree">
    <div class="tree-header">
      <h3>部门设定</h3>
      <div class="search-box">
        <el-input
          v-model="organizeStore.searchKeyword"
          placeholder="请输入搜索内容"
          size="small"
          clearable
        >
          <template #append>
            <el-button @click="handleSearch" size="small">查询</el-button>
          </template>
        </el-input>
      </div>
      <div class="tree-actions">
        <el-button
          type="primary"
          size="small"
          :icon="Plus"
          @click="handleAdd"
        >
          新增
        </el-button>
        <el-button
          size="small"
          :icon="Edit"
          @click="handleEdit"
          :disabled="!organizeStore.hasSelectedOrganize"
        >
          编辑
        </el-button>
        <el-button
          size="small"
          :icon="Delete"
          type="danger"
          @click="handleDelete"
          :disabled="!organizeStore.hasSelectedOrganize || isTopLevel"
        >
          删除
        </el-button>
      </div>
    </div>
    
    <div class="tree-content">
      <el-tree
        ref="treeRef"
        :data="organizeStore.organizeTree"
        :props="treeProps"
        :filter-node-method="filterNode"
        node-key="id"
        highlight-current
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        @node-contextmenu="handleRightClick"
      >
        <!-- <template #default="{ node, data }">
          <div class="tree-node">
            <span class="node-label">{{ node.label }}</span>
            <span class="node-code" v-if="data.code">({{ data.code }})</span>
          </div>
        </template> -->
      </el-tree>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElTree, ElInput, ElButton } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useOrganizeStore } from '@/stores/organize'
import type { OrganizeTreeNode } from '@/types'

// Props
interface Props {
  modelValue?: number // 当前选中的组织ID
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [id: number]
  'node-click': [node: OrganizeTreeNode]
  'add': []
  'edit': [node: OrganizeTreeNode]
  'delete': [node: OrganizeTreeNode]
}>()

// 使用store
const organizeStore = useOrganizeStore()

// 响应式数据
const treeRef = ref<InstanceType<typeof ElTree>>()

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 计算属性
const isTopLevel = computed(() => {
  return organizeStore.selectedOrganize?.parentId === 0
})

// 监听搜索关键词
watch(() => organizeStore.searchKeyword, (val) => {
  if (treeRef.value) {
    treeRef.value.filter(val)
  }
})

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  if (newVal && treeRef.value) {
    treeRef.value.setCurrentKey(newVal)
  }
})

// 监听组织树数据变化，自动选中根节点
watch(() => organizeStore.organizeTree, (newTree) => {
  if (newTree && newTree.length > 0 && treeRef.value) {
    // 如果没有选中任何节点，自动选中根节点
    if (!organizeStore.selectedOrganize) {
      const rootNode = newTree.find(node => node.parentId === 0) || newTree[0]
      if (rootNode) {
        setCurrentNode(rootNode.id)
        // 触发node-click事件，让父组件知道选中了根节点
        emit('node-click', rootNode)
      }
    }
  }
}, { deep: true, immediate: true })

// 方法
// 过滤节点
const filterNode = (value: string, data: OrganizeTreeNode) => {
  if (!value) return true
  return data.name.includes(value) || 
         (data.code && data.code.includes(value)) ||
         (data.abbreviation && data.abbreviation.toString().includes(value))
}

// 节点点击事件
const handleNodeClick = (data: OrganizeTreeNode) => {
  organizeStore.setSelectedOrganize(data)
  emit('update:modelValue', data.id)
  emit('node-click', data)
}

// 右键菜单事件
const handleRightClick = (event: MouseEvent, data: OrganizeTreeNode) => {
  event.preventDefault()
  organizeStore.setSelectedOrganize(data)
  emit('update:modelValue', data.id)
}

// 搜索
const handleSearch = () => {
  if (treeRef.value) {
    treeRef.value.filter(organizeStore.searchKeyword)
  }
}

// 新增
const handleAdd = () => {
  emit('add')
}

// 编辑
const handleEdit = () => {
  if (organizeStore.selectedOrganize) {
    emit('edit', organizeStore.selectedOrganize)
  }
}

// 删除
const handleDelete = () => {
  if (organizeStore.selectedOrganize && !isTopLevel.value) {
    emit('delete', organizeStore.selectedOrganize)
  }
}

// 刷新树数据
const refreshTree = () => {
  organizeStore.fetchOrganizeTree()
}

// 设置当前选中的节点
const setCurrentNode = (id: number) => {
  if (treeRef.value) {
    treeRef.value.setCurrentKey(id)
    const node = organizeStore.findOrganizeById(id)
    if (node) {
      organizeStore.setSelectedOrganize(node)
    }
  }
}

// 暴露方法给父组件
defineExpose({
  refreshTree,
  setCurrentNode,
  selectedNode: computed(() => organizeStore.selectedOrganize)
})

// 组件挂载时，如果数据还没有加载，则加载数据
onMounted(() => {
  if (organizeStore.organizeTree.length === 0) {
    organizeStore.fetchOrganizeTree()
  }
})
</script>

<style scoped lang="scss">
.organize-tree {
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
}

.tree-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;
  
  h3 {
    margin: 0 0 12px 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
  
  .search-box {
    margin-bottom: 12px;
  }
  
  .tree-actions {
    display: flex;
    gap: 8px;
  }
}

.tree-content {
  flex: 1;
  padding: 8px;
  overflow: auto;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  
  .node-label {
    flex: 1;
    font-size: 14px;
    color: #303133;
  }
  
  .node-code {
    font-size: 12px;
    color: #909399;
    margin-left: 8px;
  }
}

:deep(.el-tree-node__content) {
  height: 32px;
  padding: 0 8px;
  
  &:hover {
    background-color: #f5f7fa;
  }
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #e6f7ff;
  color: #1890ff;
}

:deep(.el-tree-node__expand-icon) {
  color: #c0c4cc;
  
  &.is-leaf {
    color: transparent;
  }
}
</style>
